import json
from collections import deque
import datetime

class WeatherDataStorage:
    def __init__(self, username, max_history=10):
        self.username = username        # 关联用户名
        self.socket = None             # socket对象存储
        self.current_data = {}         # 当前数据
        self.history = deque(maxlen=max_history)  # 固定长度的历史记录队列

    def add_data(self, state=0, people=0, temperature=0, humidity=0, pressure=0,
                wind_deg=0, wind_speed=0, light=0, co2=0, smock=0, soil=0,
                socket_obj=0):
        """
        添加新数据（自动维护10条历史记录）
        参数顺序：温度(℃), 湿度(%), 气压(hPa), 风向(°), 风速(m/s), socket对象
        """
        new_data = {
            'state':state,
            'people':people,
            'light':light,
            'timestamp': datetime.datetime.now(),
            'temperature': temperature,
            'humidity': humidity,
            'pressure': pressure,
            'wind_degree': wind_deg,
            'wind_speed': wind_speed,
            'co2': co2,
            'smock': smock,
            'soil': soil,

            'socket': socket_obj
        }

        if socket_obj == 0 :
            print("输入的socket 对象是空的!")

        self.current_data = new_data
        self.history.append(new_data)
        self.socket = socket_obj  # 更新最新socket连接

    def get_current(self):
        """获取最新一条数据（带格式化输出）"""
        if not self.current_data:
            return None
        data = self.current_data.copy()
        data['username'] = self.username
        return data

    def get_history(self):
        """获取全部历史记录（最多10条）"""
        return [{
            **item,
            'username': self.username,
            'timestamp': item['timestamp'].strftime("%Y-%m-%d %H:%M:%S")
        } for item in self.history]


bowuguanManage = WeatherDataStorage("bowuguan")
bowuguanManage.add_data(
        state=0,
        people=1,
        temperature=0,
        humidity=1,
        pressure=0,
        wind_deg=0,
        wind_speed=0,
        light=0,
        co2=0,
        smock=0,
        socket_obj =0
    )


homeManage = WeatherDataStorage("bowuguan")
homeManage.add_data(
        state=0,
        people=1,
        temperature=0,
        humidity=1,
        pressure=0,
        wind_deg=0,
        wind_speed=0,
        light=0,
        co2=0,
        smock=0,
        socket_obj =0
    )



# 把从socket 设备端接收到的数据保存到数据库中，同时保留和设备的socket的连接
def process_socket_save(data, socket_client):
    parsed = json.loads(data.decode('utf-8')) # 解析JSON
    user = parsed.get("user")
    print("process_socket_save: ", user)

    if user == "bowuguan" : # 博物馆的代码
        data_hum = parsed.get("hum") # 博物馆的数据包括 气温 湿度 是不是有人 状态(报警中或讲解中)
        data_temp = parsed.get("temp")
        data_peo = parsed.get("peo")
        data_lit = parsed.get("lit")
        print("data_hum ", data_hum,
            "data_temp ", data_temp,
            "data_peo", data_peo,
            "data_lit", data_lit)
        # 添加数据（示例参数）
        bowuguanManage.add_data(
            state= 0,
            people= data_peo,
            temperature= data_temp,
            humidity= data_hum,
            light=data_lit,
            socket_obj=socket_client  # 假设的socket对象
        )
    elif user == "home": # 智能家居
        data_hum  = parsed.get("hum") # 博物馆的数据包括 气温 湿度 是不是有人 状态(报警中或讲解中)
        data_temp = parsed.get("temp")
        data_peo  = parsed.get("peo")
        data_lit  = parsed.get("lit")
        data_co2  = parsed.get("co2")
        data_sm   = parsed.get("sm")
        data_soil = parsed.get("soil")
        print(
            "data_hum ",   data_hum,
            " data_temp ", data_temp,
            " data_peo ",  data_peo,
            " data_lit ",  data_lit,
            " data_co2 ",  data_co2,
            " data_sm ",   data_sm,
            " data_soil", data_soil
            )

        # 添加数据（示例参数）
        homeManage.add_data(
            state= 0,
            people= data_peo,
            temperature= data_temp,
            humidity= data_hum,
            light=data_lit,
            pressure=0,
            wind_deg=0,
            wind_speed=0,
            co2=data_co2,
            smock=data_sm,
            soil=data_soil,
            socket_obj=socket_client  # 假设的socket对象
        )
    else:
        print("没这条user")


# 前端界面来get到的数据，输入时前端的用户名称输入，输出是数据内容
def process_socket_get(user_name):
    if user_name == "bowuguan" :
        # 获取当前数据
        current = bowuguanManage.get_current()
        print("成功获取到数据库数据 ", user_name)
        return current
    elif user_name == "home" :
        # 获取当前数据
        current = homeManage.get_current()
        print("成功获取到数据库数据 ", user_name)
        return current
    else:
        print("没有查询数据")




if __name__ == '__main__':
    # 初始化实例（关联用户名）
    storage = WeatherDataStorage("meteorologist_01")

    # 添加数据（示例参数）
    storage.add_data(
        state=0,
        people=1,
        temperature=25.6,
        humidity=68.5,
        pressure=1013.2,
        wind_deg=135.8,
        wind_speed=3.4,
        light=0,
        socket_obj=1  # 假设的socket对象
    )

    # 添加数据（示例参数）
    storage.add_data(
        state=0,
        people=1,
        temperature=1,
        humidity=68.5,
        pressure=1013.2,
        wind_deg=135.8,
        wind_speed=3.4,
        light=0,
        socket_obj=1  # 假设的socket对象
    )
    # 获取当前数据
    current = storage.get_current()
    print(f"当前温度：{current['temperature']}℃")

    current = storage.get_current()
    print(f"当前温度：{current['temperature']}℃")

    # 查看历史记录
    history = storage.get_history()
    print(f"最近{len(history)}条记录：")
    for record in history:
        print(f"{record['timestamp']} | 风速：{record['wind_speed']}m/s")